package com.liauto.timelist.util

import android.util.Log
import okhttp3.*
import java.io.IOException
import java.util.concurrent.TimeUnit


object HttpUtil {

    private const val TAG = "HttpUtil"
    private val okHttpClient = OkHttpClient.Builder()
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .connectTimeout(10, TimeUnit.SECONDS)
        .build()

    data class Result(
        var success: Boolean = false,
        var code: Int = 0,
        var content: String = "unsuccessful"
    ){
        override fun toString(): String {
            return "Result(success=$success, code=$code, content='$content')"
        }
    }


    fun getRequest(url: String, result: (Result) -> Unit) {

        val request = Request.Builder()
            .url(url)
            .build()

        okHttpClient.newCall(request).apply {
            try {
                execute().apply {
                    Result().let { r ->
                        r.success = isSuccessful
                        r.code = code
                        r.content = (body?.string() ?: "unsuccessful").apply {
                            Log.d(
                                TAG,
                                "okhttp response $this"
                            )
                        }
                        result(r)
                    }

                }
            } catch (e: IOException) {
                Result().let { r ->
                    r.success = false
                    r.content = e.message ?: "unknown"
                    result(r)
                }

            }
        }
    }
}

